package com.shanghaionstar.remote.share;

import android.app.Activity;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.ToggleButton;

import com.nostra13.universalimageloader.core.ImageLoader;
import com.onstar.cn.common.exception.OnStarException;
import com.onstar.cn.common.util.CommonUtil;
import com.onstar.cn.framework.annotation.FindViewById;
import com.onstar.cn.framework.mvp.base.core.AppScheduler;
import com.onstar.cn.framework.mvp.base.core.BaseFragment;
import com.onstar.cn.framework.utils.RxBus;
import com.onstar.cn.framework.utils.RxSubscriptions;
import com.onstar.cn.map.util.ToastUtil;
import com.onstar.cn.smart.BaseResponse;
import com.onstar.cn.vehicle.response.AuthorizedSubscriberResponse;
import com.onstar.cn.weight.ProgressLayout;
import com.shanghaionstar.OnstarApplication;
import com.shanghaionstar.R;
import com.shanghaionstar.home.adapter.CommonAdapter;
import com.shanghaionstar.home.adapter.ViewHolder;
import com.shanghaionstar.remote.share.presenters.ShareRemoteListPresenter;
import com.shanghaionstar.remote.share.views.IShareRemoteListView;
import com.shanghaionstar.utils.AlertDialogUtil;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import rx.Subscription;
import rx.functions.Action1;

/**
 * Created by 11203rl on 2017/5/18.
 */

public class ShareRoleListFrg extends BaseFragment implements IShareRemoteListView {
    public static final int UPDATE_SUC = 0x100;

    @FindViewById(R.id.authorize_lv)
    private ListView mAuthorizeLv;
    @FindViewById(R.id.share_pl)
    private ProgressLayout mSharePl;
    @FindViewById(R.id.no_data_tv)
    private TextView noDataTv;

    private ShareRemoteListPresenter remoteListPresenter;
    private List<AuthorizedSubscriberResponse> mList;
    private CommonAdapter commonAdapter;


    @Override
    public int getLayoutId() {
        return R.layout.remote_card_list;
    }

    private Subscription mUpdateRx;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (isFirstLoad()) {
            remoteListPresenter = new ShareRemoteListPresenter(baseActivity.getScheduler(), baseActivity);
            remoteListPresenter.setView(this);
            mUpdateRx = RxBus.getDefault().toObserverable(UPDATE_SUC,String.class).subscribeOn(new AppScheduler().backgroundThread())
                    .observeOn(new AppScheduler().mainThread())
                    .subscribe(new Action1<String>() {
                        @Override
                        public void call(String s) {
                            AlertDialogUtil.showAlertDialog(baseActivity,R.string.remote_share_dia_title,R.string.remote_share_dia_msg);
                        }
                    });
            RxSubscriptions.add(mUpdateRx);
        }
        remoteListPresenter.getAuthorizedSubs();
    }

    @Override
    public void setLoading(boolean isLoading) {
        mSharePl.setVisibility(isLoading ? View.VISIBLE : View.GONE);
    }

    @Override
    public void onResponseError(OnStarException e) {

        AlertDialogUtil.showDialogByOnstarException(baseActivity, e);


    }


    @Override
    public void onReponseSuccess(Object object) {
        if (CommonUtil.isNull(object))
            return;
        if (object instanceof BaseResponse) {
            commonAdapter.notifyDataSetChanged();
            return;
        }
        if (object instanceof java.util.List) {
            mList = (List<AuthorizedSubscriberResponse>) object;
            if(mList !=null && !mList.isEmpty())
                setAdapter();
            else
                noDataTv.setVisibility(View.VISIBLE);
            return;
        }
    }

    private void setAdapter() {
        noDataTv.setVisibility(View.GONE);
        commonAdapter = new CommonAdapter<AuthorizedSubscriberResponse>(baseActivity, mList, R.layout.remote_share_card_item) {
            @Override
            public void convert(final ViewHolder holder, final AuthorizedSubscriberResponse authorizedSubscriberResponse) {
                String status = authorizedSubscriberResponse.getAuthorizeStatus();
                final boolean isAuthorized = !TextUtils.isEmpty(status) && status.equalsIgnoreCase("1");
                holder.setText(R.id.authorize_tv, isAuthorized ? R.string.remote_share_authorized : R.string.remote_share_unauthorized);
                holder.setSelect(R.id.authorize_tb, isAuthorized);
                ImageView headIv = holder.getView(R.id.head_iv);
                ImageLoader.getInstance().displayImage(authorizedSubscriberResponse.getFaceUrl(),
                        headIv, OnstarApplication.getOptions(true, false, R.drawable.remote_card_head));
                String context = authorizedSubscriberResponse.getContext();
                context = TextUtils.isEmpty(context) ? "" : (context.contains("@") ? CommonUtil.replaceString(context, true) : CommonUtil.replaceString(context, false));
                holder.setText(R.id.phone_tv, context);
                String dateStr = authorizedSubscriberResponse.getEndDate();
                dateStr = getLocalDate(dateStr);
                String expiredDate = getString(R.string.remote_share_expired);
                String limit = authorizedSubscriberResponse.getLimit();
                boolean isLimit = limit!=null && limit.equalsIgnoreCase("0");
                holder.setText(R.id.expired_tv, isAuthorized ? (isLimit?getString(R.string.remote_share_no_limit):String.format(expiredDate, dateStr)):"");
                String roleType = authorizedSubscriberResponse.getRoleType();
                String roleTxt = TextUtils.isEmpty(roleType) ? "" : (roleType.equalsIgnoreCase("DRIVER") ? getString(R.string.remote_share_driver) : getString(R.string.remote_share_proxy));
                holder.setText(R.id.role_btn, roleTxt);
                holder.setVisible(R.id.edit_iv, isAuthorized);
                ToggleButton tb = holder.getView(R.id.authorize_tb);
                tb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                    @Override
                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                        if (isAuthorized) {
                            remoteListPresenter.setAuthorizedStatus(buttonView, holder, authorizedSubscriberResponse);
                        } else {
                            buttonView.setSelected(true);
                            switchToEdit(authorizedSubscriberResponse);
                        }
                    }
                });
                holder.setOnClickListener(R.id.role_rl, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (isAuthorized)
                            switchToEdit(authorizedSubscriberResponse);
                    }
                });
            }
        };
        mAuthorizeLv.setAdapter(commonAdapter);
    }


    public void switchToEdit(AuthorizedSubscriberResponse authorizedSubscriberResponse) {
        ShareTimeEditFrg editFrg = new ShareTimeEditFrg();
        Bundle bun = new Bundle();
        bun.putSerializable("authorize", authorizedSubscriberResponse);
        editFrg.setArguments(bun);
        baseActivity.changeFragment(baseActivity.getSupportFragmentManager(), editFrg, ShareTimeEditFrg.class, true);
    }

    public String getLocalDate(String dateStr) {
        try {
            SimpleDateFormat sim = new SimpleDateFormat("yyyy-MM-dd");
            Date ticDate = sim.parse(dateStr);
            String date = ticDate.toLocaleString();
            return date.substring(0, date.indexOf(" "));
        } catch (Exception e) {

        }
        return TextUtils.isEmpty(dateStr) ? "" : dateStr;
    }

    @Override
    public Activity onActivity() {
        return getActivity();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        RxSubscriptions.remove(mUpdateRx);
    }

    @Override
    public void onRemoteShareSetFailed(OnStarException e) {
        ToastUtil.showShort(OnstarApplication.getApplication(),R.string.remote_share_set_failed);
    }
}
